package com.yb.xczx.cloud.auth.generator;

import com.yb.core.constant.RedisKeyConstant;
import com.yb.core.enums.LoginTypeEnum;
import com.yb.core.exception.XczxBusinessException;
import com.yb.core.model.XczxLoginUser;
import com.yb.xczx.cache.manager.api.XczxStringCacheManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
public class XczxLoginCodeGenerator implements XczxCodeGenerator {

    XczxStringCacheManager xczxStringCacheManager;

    public XczxLoginCodeGenerator(XczxStringCacheManager xczxStringCacheManager){
        this.xczxStringCacheManager=xczxStringCacheManager;
    }
    @Override
    public String generate(XczxLoginUser xczxLoginUser) {

        String username = xczxLoginUser.getUsername();

        if(!StringUtils.hasText(username)){
            log.info("XczxLoginCodeGenerator generate username is empty",username);
            throw new XczxBusinessException("用户名username不能为空");
        }

        String code = UUID.randomUUID().toString().replaceAll("-", "");

        log.info("XczxLoginCodeGenerator generate for {} code {}",username,code);

        xczxStringCacheManager.expire(String.format(RedisKeyConstant.LOGIN_USER_LOGINCODE_KEY,username),code,60, TimeUnit.SECONDS);

        return code;
    }

    @Override
    public boolean support(String loginType) {
        return LoginTypeEnum.LOGIN_CODE.getLoginType().equals(loginType);
    }
}
